<?php

namespace app\api\model;

use app\common\model\User;
use think\Db;
use think\Model;

class Order extends Model {

	// 表名
	protected $name = 'shop_order';

	// 自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';

	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';

	protected static function init() {
//		self::afterInsert( function ( $row ) {
//			if ( $row['score'] > 0 ) {
//				$userModel = new User();
//				$userModel->score( - $row['score'], $row['user_id'], '积分抵扣' );
//			}
//		} );
//
//		self::beforeUpdate( function ( $row ) {
//			$changed = $row->getChangedData();
//			//如果有修改密码
//			if ( isset( $changed['order_status'] ) ) {
//				switch ( $changed['order_status'] ) {
//					case 11:
//						Db::name( 'user_coupon' )->where( ['order_id' => $row['id']] )->update( ['status' => 1] );
//						Db::name( 'user_voucher' )->where( ['order_id' => $row['id']] )->update( ['status' => 1] );
//						break;
//				}
//			}
//		} );
	}

	public function getCreatetimeAttr( $value ) {
		return date( 'Y-m-d H:i', $value );
	}

	public function goodsDetail() {
		return $this->hasMany( 'OrderGoods', 'order_id', 'id' );
	}

	/**
	 * 收货
	 */
	public function receipt( $id ) {
		$info = $this->where( ['id' => $id, 'order_status' => 3] )->find();
		if ( empty( $info ) ) {
			return false;
		}
		$row = $info->save( ['order_status' => 4, 'receipt_time' => time()] );
		//赠送积分
//		if ( $info['give_score'] > 0 ) {
//			$model = new User();
//			$model->score( $info['give_score'], $info['user_id'], "赠送积分" );
//		}
		return $row;
	}

	/**
	 * 取消
	 */
	public function cancel( $ids ) {
		$row      = $this->where( ['id' => ['in', $ids], 'order_status' => 1] )->setField( 'order_status', 11 );
		$goodList = Db::name( 'shop_order_goods' )->where( ['order_id' => ['in', $ids]] )->select();
		foreach ( $goodList as $k => $v ) {
			// 下单减库存
			$v['deduct_stock_type'] === '10' && $deductStockData[] = [
				'goods_spec_id' => $v['goods_spec_id'],
				'stock_num'     => ['inc', $v['total_num']]
			];
		}
		// 更新商品库存
		!empty( $deductStockData ) && ( new ShopGoodsSpec() )->isUpdate()->saveAll( $deductStockData );
		return $row;
	}

}
